package com.fan.leetcode;

import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.stream.IntStream;

/**
 * 8. 字符串转换整数 (atoi)
 *
 * @author ZhangFan
 * @since 2021/9/4 下午 7:44
 */
public class Question8 {
    @Test
    void test() {
        System.out.println("myAtoi() = " + myAtoi(""));
    }

    public int myAtoi(String s) {
        char[] chars = s.toCharArray();
        int index = 0;
        char symbol = '+';
        StringBuilder num = new StringBuilder("0");
        while (index < s.length() && chars[index] == ' ') {
            index++;
        }
        if (index < s.length() && (chars[index] == '+' || chars[index] == '-')) {
            symbol = chars[index];
            index++;
        }
        while (index < s.length() && chars[index] >= 48 && chars[index] <= 57) {
            num.append(chars[index]);
            index++;
        }
        int aInt = 0;
        try {
            aInt = Integer.parseInt(symbol + num.toString());
        } catch (NumberFormatException e) {
            if (symbol == '-') {
                aInt = -2147483648;
            }
            if (symbol == '+') {
                aInt = 2147483647;
            }
        }
        return aInt;
    }
}
